import { sys, view } from "cc";
import UrlEnum from "../Res/UrlEnum";
import Http, { IHttpMethod } from "../Net/Http";
import SdkInterface from "./SdkInterface";
import SdkTool from "./SdkTool";
import { ViewManager } from "../../Game/module/base/ViewManager";
import { SocketManager } from "../../Game/module/socket/SocketManager";
import TimerMgr from "../Timer/TimerMgr";
import ProtoBufManager from "../../Game/proto/ProtoBufManager";
import EventMgr from "../Event/EventMgr";
import { arrayBuffer } from "stream/consumers";
import { common, http } from "../../Game/proto/protoCmd";
import { GameModels } from "../../Game/module/socket/GameModels";
import { StringUtils } from "../Utils/StringUtils";
import Log from "../Log/Log";
export default class BaseSdk implements SdkInterface {
    /**
     * 初始化
     * @param callback 初始化成功后回调
     * @param target 监听对象
     */
    public init(callback: Function, target: Object): void {
        Log.ins.log(1, `BaseSdk init`);
        SdkTool.ins.sidebar = true;
        SdkTool.ins.isSidebar = false;
    }

    /**
     * 登录
     * @param callback 登录成功后回调
     * @param target 监听对象
     */
    public login(): void {
        Log.ins.log(1, `BaseSdk login`);
        ViewManager.ins.showloading();
        //{"openid":"${SdkTool.ins.openid}"}
        const reqData = ProtoBufManager.ins.http.ReqEntry.create();
        reqData.Token = SdkTool.ins.openid;
        reqData.ChannelId = ProtoBufManager.ins.common.EChannelId.Visitor;
        const data: Uint8Array = ProtoBufManager.ins.http.ReqEntry.encode(reqData).finish();
        // const token: string = SdkTool.ins.openid;
        // const channelId: common.EChannelId = SdkTool.ins.channelId;
        // const json = `{"Token":"${token}","ChannelId":"${channelId}"}`;
        //?Token=${token}&ChannelId=${channelId}
        Http.ins.request(`${UrlEnum.httpUrl}`, data.slice().buffer, (data) => {
            if (!data) {
                EventMgr.emit(`serverError`);
                return;
            }
            ViewManager.ins.removeLoading();
            const rawData = new Uint8Array(data);
            const buf: http.RespEntry = ProtoBufManager.ins.http.RespEntry.decode(rawData);
            if (buf.ErrCode != ProtoBufManager.ins.common.ErrorCode.OK) {
                Log.ins.log(4, `登录游戏服失败,错误码:${buf.ErrCode}`);
                EventMgr.emit(`baseLogin`, false);
                return;
            }
            if (!buf.WSUrl.Host) {
                EventMgr.emit(`serverError`);
                return;
            }
            UrlEnum.socketip = `${buf.WSUrl.Host}:${buf.WSUrl.Port}`;
            Log.ins.log(2, `登录游戏服成功,玩家uid:${buf.UId}`);
            Log.ins.log(2, `游戏大厅路由:${buf.LobbyRoute}`);
            Log.ins.log(2, `游戏服地址:${UrlEnum.socketip}`);
            Log.ins.log(2, `${buf.IsNewAccount ? "是新用户" : "是老用户"}`);
            SdkTool.ins.isFirst = buf.IsNewAccount;
            GameModels.info.playerInfo.UserId = buf.UId;
            GameModels.info.playerInfo.LobbyRoute = buf.LobbyRoute;
            SocketManager.ins.connect();
        }, IHttpMethod.POST);
    }
    public isStringNumericStrict(str) {
        const num = parseFloat(str);
        return !isNaN(num) && Number.isFinite(num);
    }
    /**
     * 登出
     */
    public logout(): void {
        Log.ins.log(1, "BaseSdk logout");
    }

    /**
     * 退出
     */
    public exit(): void {
        Log.ins.log(1, "BaseSdk exit");
    }

    /**
     * 切换账号
     */
    public switchLogin(): void {
        Log.ins.log(1, "BaseSdk switchLogin");
    }

    /**
     * 数据上报
     * @param param 参数
     */
    public report(...param: any[]): void {
        Log.ins.log(1, "BaseSdk report");
    }

    /**
     * 数据上报
     * @param param 参数
     */
    public pay(...param: any[]): void {
        Log.ins.log(1, "BaseSdk pay");
    }

    /**
     * 播放广告
     */
    createRewardAd(): void {
    }
    /**
     * 播放广告
     */
    playRewardAd(callback: Function, target: any): void {
        ViewManager.ins.showloading();
        TimerMgr.ins.add(2000, 1, () => {
            ViewManager.ins.removeLoading();
            callback.call(target, true);
        }, this);
    }
    /**
     * 显示banner广告
     */
    showBannerAd(show: boolean): void {
    }
    /**
     * 显示插屏广告
     */
    showInterstitialAd(): void { }
    /**
     * 显示自定义广告
     */
    showCustomAd(show, top?, left?): void { }
    /**
     * 主动拉起转发(小程序)
     */
    shareAppMessage(title: string, query: any = null, shareCallback: any = null): void {
        if (shareCallback) {
            shareCallback();
        }
        ViewManager.ins.showtips(`当前平台不支持分享`);

    }
    getAppParam(): any {
        return ``;
    }
    reconnect(): void {
        ViewManager.ins.showtips(`已掉线，正在重新连接...`);
        this.login();
    }
    public navigateToScene(): void {
        SdkTool.ins.isSidebar = true;
    }
    public getMenuButtonBoundingClientRect(): any {
        SdkTool.ins.topmenu = 0;
    }
    public setImRankData(val): void {

    }
    public getImRankList(): void {
        ViewManager.ins.showtips(`当前平台不支持排行榜`);
    }
    public vibrateShort(): void {

    }
    public setClipboardData(val: string): void {
        this.copyText(val);
    }
    private copyText(text) {
        if (navigator.clipboard) {
            navigator.clipboard.writeText(text)
                .then(() => {
                    Log.ins.log(2, text);
                    ViewManager.ins.showtips(`复制成功`);
                })
                .catch(err => Log.ins.log(3, '现代 API 复制失败，尝试传统方法:', err));
        } else {
            this.copyToClipboardLegacy(text); // 调用上述传统方法
        }
    }
    private copyToClipboardLegacy(text) {
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        try {
            const success = document.execCommand('copy');
            if (success) {
                ViewManager.ins.showtips(`复制成功`);
                Log.ins.log(2, text);
            } else {
                Log.ins.log(3, '复制失败');
            }
        } catch (err) {
            Log.ins.log(3, '复制异常:', err);
        } finally {
            document.body.removeChild(textarea);
        }
    }
}